<template>
  <div class="container">
    <h1 class="text-2xl font-bold mb-4">维护分析</h1>
    
    <div class="mb-4 flex items-center space-x-4">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :shortcuts="dateShortcuts"
        value-format="YYYY-MM-DD"
        @change="handleDateChange"
      />
      <el-select v-model="selectedVehicle" placeholder="选择车辆" clearable @change="loadData">
        <el-option
          v-for="vehicle in vehicles"
          :key="vehicle.id"
          :label="vehicle.vehicleNo"
          :value="vehicle.id"
        />
      </el-select>
      <el-select v-model="maintenanceType" placeholder="维护类型" clearable @change="loadData">
        <el-option label="全部" value="" />
        <el-option label="保养" value="service" />
        <el-option label="年检" value="inspection" />
        <el-option label="维修" value="repair" />
      </el-select>
      <el-button type="primary" @click="loadData">查询</el-button>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">维护总次数</h2>
        <p class="text-3xl font-bold text-blue-500">{{ stats.totalMaintenance }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">维护总费用</h2>
        <p class="text-3xl font-bold text-red-500">{{ formatCurrency(stats.totalCost) }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">平均每车维护次数</h2>
        <p class="text-3xl font-bold text-green-500">{{ stats.avgMaintenancePerVehicle.toFixed(1) }}</p>
      </el-card>
      <el-card shadow="hover" class="text-center">
        <h2 class="text-lg font-medium text-gray-500 mb-1">平均每车维护费用</h2>
        <p class="text-3xl font-bold text-yellow-500">{{ formatCurrency(stats.avgCostPerVehicle) }}</p>
      </el-card>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>维护类型费用占比</span>
          </div>
        </template>
        <div ref="maintenanceTypeChart" class="h-full w-full"></div>
      </el-card>
      
      <el-card shadow="hover" class="h-80">
        <template #header>
          <div class="flex justify-between items-center">
            <span>维护费用趋势</span>
            <el-radio-group v-model="trendTimeUnit" size="small" @change="updateTrendChart">
              <el-radio-button label="month">月度</el-radio-button>
              <el-radio-button label="quarter">季度</el-radio-button>
              <el-radio-button label="year">年度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="maintenanceTrendChart" class="h-full w-full"></div>
      </el-card>
    </div>
    
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <span>车辆维护对比</span>
          <el-radio-group v-model="vehicleCompareMode" size="small" @change="updateVehicleChart">
            <el-radio-button label="frequency">维护次数</el-radio-button>
            <el-radio-button label="cost">维护费用</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div ref="vehicleMaintenanceChart" style="height: 400px; width: 100%"></div>
    </el-card>
    
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span>维护明细</span>
          <el-button type="primary" size="small" @click="exportReport">导出报表</el-button>
        </div>
      </template>
      <el-table :data="maintenanceRecords" border stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="typeName" label="维护类型" width="100">
          <template #default="scope">
            <el-tag :type="getMaintenanceTypeTag(scope.row.type)">
              {{ scope.row.typeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="维护项目" min-width="180" />
        <el-table-column prop="mileage" label="里程(km)" width="120" />
        <el-table-column prop="location" label="维护地点" min-width="150" />
        <el-table-column prop="cost" label="费用(元)" width="120">
          <template #default="scope">
            {{ scope.row.cost.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRecords"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'MaintenanceAnalysisView',
  setup() {
    // 图表实例
    let maintenanceTypeChartInstance = null
    let maintenanceTrendChartInstance = null
    let vehicleMaintenanceChartInstance = null
    
    // 图表DOM引用
    const maintenanceTypeChart = ref(null)
    const maintenanceTrendChart = ref(null)
    const vehicleMaintenanceChart = ref(null)
    
    // 数据状态
    const vehicles = ref([])
    const selectedVehicle = ref('')
    const dateRange = ref([])
    const maintenanceType = ref('')
    const trendTimeUnit = ref('month')
    const vehicleCompareMode = ref('frequency')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalRecords = ref(0)
    const maintenanceRecords = ref([])
    
    // 统计数据
    const stats = reactive({
      totalMaintenance: 0,
      totalCost: 0,
      avgMaintenancePerVehicle: 0,
      avgCostPerVehicle: 0
    })
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近三个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        },
      },
      {
        text: '最近半年',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
          return [start, end]
        },
      },
      {
        text: '今年',
        value: () => {
          const end = new Date()
          const start = new Date(new Date().getFullYear(), 0, 1)
          return [start, end]
        },
      },
    ]
    
    // 模拟数据
    const mockData = {
      // 维护类型分布
      maintenanceTypes: [
        { value: 38000, name: '保养费用' },
        { value: 22000, name: '维修费用' },
        { value: 8000, name: '年检费用' }
      ],
      // 维护趋势
      maintenanceTrend: {
        categories: ['1月', '2月', '3月', '4月', '5月', '6月'],
        series: [
          {
            name: '保养费用',
            data: [5000, 6800, 5600, 7200, 6400, 7000]
          },
          {
            name: '维修费用',
            data: [3000, 4200, 3800, 4500, 3200, 3300]
          },
          {
            name: '年检费用',
            data: [0, 3500, 0, 2800, 0, 1700]
          }
        ]
      },
      // 车辆对比
      vehicleComparison: {
        vehicles: ['京A12345', '京B67890', '京C54321', '京D98765', '京E13579'],
        frequency: [12, 9, 8, 10, 7],
        cost: [16800, 12500, 11800, 14200, 13000]
      },
      // 维护记录
      maintenanceRecords: [
        {
          date: '2023-06-15',
          vehicleNo: '京A12345',
          type: 'service',
          typeName: '保养',
          description: '常规保养（更换机油、机滤）',
          mileage: 10000,
          location: '北京市海淀区4S店',
          cost: 1200
        },
        {
          date: '2023-06-10',
          vehicleNo: '京B67890',
          type: 'repair',
          typeName: '维修',
          description: '更换刹车片',
          mileage: 25000,
          location: '北京市朝阳区汽车修理厂',
          cost: 1800
        },
        {
          date: '2023-06-05',
          vehicleNo: '京C54321',
          type: 'inspection',
          typeName: '年检',
          description: '年度检验',
          mileage: 35000,
          location: '北京市西城区车管所',
          cost: 500
        }
      ]
    }
    
    // 初始化
    onMounted(() => {
      // 初始化日期范围为近三个月
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      dateRange.value = [formatDate(start), formatDate(end)]
      
      // 加载数据
      loadVehicles()
      loadData()
      
      // 初始化图表
      nextTick(() => {
        initCharts()
      })
    })
    
    // 加载车辆列表
    const loadVehicles = async () => {
      try {
        // 实际项目中应从API获取
        /*
        const response = await axios.get('/api/vehicles')
        vehicles.value = response
        */
        
        // 模拟数据
        vehicles.value = [
          { id: 1, vehicleNo: '京A12345' },
          { id: 2, vehicleNo: '京B67890' },
          { id: 3, vehicleNo: '京C54321' },
          { id: 4, vehicleNo: '京D98765' },
          { id: 5, vehicleNo: '京E13579' }
        ]
      } catch (error) {
        ElMessage.error('获取车辆列表失败')
        console.error('获取车辆列表失败:', error)
      }
    }
    
    // 加载数据
    const loadData = async () => {
      try {
        // 实际项目中应从API获取数据
        /*
        const params = {
          startDate: dateRange.value[0],
          endDate: dateRange.value[1],
          vehicleId: selectedVehicle.value,
          maintenanceType: maintenanceType.value,
          page: currentPage.value,
          size: pageSize.value
        }
        const response = await axios.get('/api/reports/maintenance-analysis', { params })
        // 使用API返回的数据更新统计和图表
        */
        
        // 使用模拟数据更新
        maintenanceRecords.value = mockData.maintenanceRecords
        totalRecords.value = mockData.maintenanceRecords.length
        
        // 更新统计数据
        stats.totalMaintenance = 46
        stats.totalCost = 68000
        stats.avgMaintenancePerVehicle = 9.2
        stats.avgCostPerVehicle = 13600
        
        // 更新图表
        updateCharts()
      } catch (error) {
        ElMessage.error('加载数据失败')
        console.error('加载数据失败:', error)
      }
    }
    
    // 初始化图表
    const initCharts = () => {
      initMaintenanceTypeChart()
      initMaintenanceTrendChart()
      initVehicleMaintenanceChart()
    }
    
    // 更新所有图表
    const updateCharts = () => {
      nextTick(() => {
        initMaintenanceTypeChart()
        updateTrendChart()
        updateVehicleChart()
      })
    }
    
    // 初始化维护类型分布图表
    const initMaintenanceTypeChart = () => {
      if (maintenanceTypeChartInstance) {
        maintenanceTypeChartInstance.dispose()
      }
      
      maintenanceTypeChartInstance = echarts.init(maintenanceTypeChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}元 ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          data: mockData.maintenanceTypes.map(item => item.name)
        },
        series: [
          {
            name: '维护费用',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: mockData.maintenanceTypes
          }
        ]
      }
      
      maintenanceTypeChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        maintenanceTypeChartInstance.resize()
      })
    }
    
    // 初始化维护趋势图表
    const initMaintenanceTrendChart = () => {
      if (maintenanceTrendChartInstance) {
        maintenanceTrendChartInstance.dispose()
      }
      
      maintenanceTrendChartInstance = echarts.init(maintenanceTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            let sum = 0
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}元<br/>`
              sum += param.value
            })
            result += `<div style="margin-top:5px;border-top:1px solid #ccc;padding-top:5px"><b>总费用: ${sum}元</b></div>`
            return result
          }
        },
        legend: {
          data: mockData.maintenanceTrend.series.map(item => item.name),
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: mockData.maintenanceTrend.categories
        },
        yAxis: {
          type: 'value',
          name: '金额(元)'
        },
        series: mockData.maintenanceTrend.series.map(item => ({
          name: item.name,
          type: 'line',
          stack: '总量',
          areaStyle: {
            opacity: 0.3
          },
          emphasis: {
            focus: 'series'
          },
          data: item.data,
          itemStyle: {
            color: getColorForMaintenanceType(item.name)
          }
        }))
      }
      
      maintenanceTrendChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        maintenanceTrendChartInstance.resize()
      })
    }
    
    // 更新趋势图表
    const updateTrendChart = () => {
      initMaintenanceTrendChart()
    }
    
    // 初始化车辆维护对比图表
    const initVehicleMaintenanceChart = () => {
      if (vehicleMaintenanceChartInstance) {
        vehicleMaintenanceChartInstance.dispose()
      }
      
      vehicleMaintenanceChartInstance = echarts.init(vehicleMaintenanceChart.value)
      
      const data = vehicleCompareMode.value === 'frequency' ? 
        mockData.vehicleComparison.frequency : mockData.vehicleComparison.cost
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const value = params[0].value
            const unit = vehicleCompareMode.value === 'frequency' ? '次' : '元'
            return `${params[0].name}: ${value}${unit}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: mockData.vehicleComparison.vehicles,
          axisLabel: {
            interval: 0
          }
        },
        yAxis: {
          type: 'value',
          name: vehicleCompareMode.value === 'frequency' ? '维护次数' : '维护费用(元)'
        },
        series: [
          {
            name: vehicleCompareMode.value === 'frequency' ? '维护次数' : '维护费用',
            type: 'bar',
            barWidth: '50%',
            data: data,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#6193FE' },
                { offset: 1, color: '#92B7FF' }
              ])
            },
            label: {
              show: true,
              position: 'top',
              formatter: vehicleCompareMode.value === 'frequency' ? '{c}次' : '{c}元'
            }
          }
        ]
      }
      
      vehicleMaintenanceChartInstance.setOption(option)
      
      // 响应式调整大小
      window.addEventListener('resize', () => {
        vehicleMaintenanceChartInstance.resize()
      })
    }
    
    // 更新车辆对比图表
    const updateVehicleChart = () => {
      initVehicleMaintenanceChart()
    }
    
    // 处理日期变化
    const handleDateChange = () => {
      loadData()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    // 获取维护类型标签颜色
    const getMaintenanceTypeTag = (type) => {
      const types = {
        service: 'primary',
        repair: 'danger',
        inspection: 'warning'
      }
      return types[type] || ''
    }
    
    // 获取维护类型对应颜色
    const getColorForMaintenanceType = (typeName) => {
      const colors = {
        '保养费用': '#409EFF',
        '维修费用': '#F56C6C',
        '年检费用': '#E6A23C'
      }
      return colors[typeName] || '#409EFF'
    }
    
    // 导出报表
    const exportReport = () => {
      ElMessage.success('报表导出成功')
      // 实际项目中应调用导出API
      // window.location.href = '/api/reports/maintenance-analysis/export?startDate=' + dateRange.value[0] + '&endDate=' + dateRange.value[1]
    }
    
    // 格式化货币
    const formatCurrency = (value) => {
      return value.toLocaleString('zh-CN', { 
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }) + '元'
    }
    
    // 日期格式化
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    return {
      vehicles,
      selectedVehicle,
      dateRange,
      dateShortcuts,
      maintenanceType,
      trendTimeUnit,
      vehicleCompareMode,
      maintenanceRecords,
      currentPage,
      pageSize,
      totalRecords,
      stats,
      maintenanceTypeChart,
      maintenanceTrendChart,
      vehicleMaintenanceChart,
      loadData,
      handleDateChange,
      handleSizeChange,
      handleCurrentChange,
      updateTrendChart,
      updateVehicleChart,
      getMaintenanceTypeTag,
      formatCurrency,
      exportReport
    }
  }
}
</script> 